﻿using System;
using System.Collections.Generic;
using System.Linq;
using HtmlAgilityPack;


namespace PodcastGenerator
{
    public class Scraper : IScraper
    {
        private readonly ISermonBuilder _sermonBuilder;

        public Scraper(ISermonBuilder sermonBuilder)
        {
            _sermonBuilder = sermonBuilder;
        }

        public IEnumerable<ISermon> Scrape(HtmlDocument document)
        {
            var dataRowCollection = document.DocumentNode.SelectNodes("//table[@bordercolor='#eaf0f6']//tbody//tr");
            if (dataRowCollection == null)
                return new List<ISermon>();
            
            var dataCellCollection = new List<HtmlNode>();

            dataRowCollection.Where(row => !row.InnerHtml.Contains("underline"))
                .ToList()
                .ForEach(p => dataCellCollection.AddRange(p.SelectNodes("td")));

            var sermons = dataCellCollection.Skip(7)
                .Select((dataCell, index) => new DataCell(index, dataCell.InnerText, dataCell.InnerHtml ))
                .GroupBy(g => g.Index / 6)
                .Select(groupedRows => _sermonBuilder.Build(groupedRows.ToArray()));


            return sermons;
        }

        public class DataCell
        {
            public int Index { get; set; }
            public string InnerText { get; set; }
            public string InnerHtml { get; set; }

            public DataCell(int index, string innerText, string innerHtml)
            {
                Index = index;
                InnerText = innerText;
                InnerHtml = innerHtml;
            }
        }
    }
}
